<script setup>
import { ref, onMounted, inject } from "vue";
import { ElMessage } from "element-plus";
import { Delete, Edit, Search, Close, Check, Grid } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { BREADCRUMBS, SEXS, SEX_OPTIONS, AVATAR } from "@/plugins/global";

const axios = inject("axios"), router = useRouter();

// ---- 组件加载：重设面包屑/计算数据表格高度/查询客户集。
onMounted(() => {
  BREADCRUMBS.splice(0, BREADCRUMBS.length,
    { label: "客户列表", path: "/home/customer_list" }
  );
  queryCustomers();
});
// ---- 查询客户集。
const customers = ref([]), customerCondition = ref({
  "customerInfoFull": null,
  "customerIdOrder": "ASC",
  "customerGteBirthdayStr": null,
  "customerLteBirthdayStr": null
});
const customerTotal = ref(null), customerPages = ref({
  "page": 1,
  "num": 10,
  "total": true
})
const queryCustomers = () => {
  axios.get("/api/cms-web/customer/query/universes", {
    params: {
      "page": customerPages.value.page,
      "num": customerPages.value.num,
      "total": customerPages.value.total,
      "customerInfoFull": customerCondition.value.customerInfoFull,
      "customerIdOrder": customerCondition.value.customerIdOrder,
      "customerGteBirthdayStr": customerCondition.value.customerGteBirthdayStr,
      "customerLteBirthdayStr": customerCondition.value.customerLteBirthdayStr
    }
  }).then((response) => {
    if (response.data.success) {
      customers.value = response.data.data.data.map(customer => {
        const { content, highlightFields } = customer;
        return {
          customerId: content.customerId,
          customerAccount: highlightFields.customerAccount ? highlightFields.customerAccount[0] : content.customerAccount,
          phoneNumber: highlightFields.phoneNumber ? highlightFields.phoneNumber[0] : content.phoneNumber,
          name: highlightFields.name ? highlightFields.name[0] : content.name,
          sex: content.sex,
          birthdayStr: content.birthdayStr,
          disable: content.disable
        };
      });
      customerTotal.value = response.data.data.total;
    } else {
      ElMessage.error(response.data.message);
    }
  });
};

// ---- 查询排序客户集。
const queryOrderCustomers = ({ column, prop, order }) => {
  if (prop === "customerId") {
    customerCondition.value.customerIdOrder = order ? (order === "ascending" ? "ASC" : "DESC") : null;
  }
  queryCustomers();
};

// ---- 禁用客户：禁用/启用指定客户。
const disableCustomer = (customer, disable) => {
  axios.put("/api/cms-web/oauth/disable/customer", {
    "customerId": customer.customerId,
    "customerAccount": customer.customerAccount,
    "disable": disable
  }).then((response) => {
    if (response.data.success) {
      ElMessage.success(disable ? "禁用成功！" : "启用成功！");
      queryCustomers();
    } else {
      ElMessage.error(response.data.message);
    }
  });
};

// ---- 删除客户准备：展示删除弹框，并记录删除客户。
const customerDeleteDialogDisable = ref(false), customerDelete = ref(null);
const deleteCustomerPrepare = (customer) => {
  customerDeleteDialogDisable.value = true;
  customerDelete.value = customer;
};
// ---- 删除客户确认：正式删除客户，并隐藏删除弹窗。
const deleteCustomerConfirm = () => {
  axios.delete("/api/cms-web/oauth/customer/delete", {
    params: {
      "customerId": customerDelete.value.customerId,
      "customerAccount": customerDelete.value.customerAccount
    }
  }).then((response) => {
    if (response.data.success) {
      ElMessage.success("删除成功！");
      queryCustomers();
      customerDeleteDialogDisable.value = false;
    } else {
      ElMessage.error(response.data.message);
    }
  });
};
</script>

<template>
  <div class="customer-page-div-class">
    <!-- 客户条件域 -->
    <div style="width: 100%;">
      <el-form :inline="true" :model="customerCondition">
        <el-form-item label="信息">
          <el-input v-model="customerCondition.customerInfoFull" placeholder="账号/手机号码/名称" :prefix-icon="Search"
            clearable style="width: 200px;" />
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker v-model="customerCondition.customerGteBirthdayStr" type="date" placeholder="开始（>=）"
            format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
          <span>&nbsp;&nbsp;~&nbsp;&nbsp;</span>
          <el-date-picker v-model="customerCondition.customerLteBirthdayStr" type="date" placeholder="结束（<=）"
            format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryCustomers()">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 客户域 -->
    <div class="customer-table-div-class">
      <el-table :data="customers" height="100%" stripe @sort-change="queryOrderCustomers">
        <el-table-column prop="customerId" label="ID" sortable="custom" align="center" />
        <el-table-column prop="customerAccount" label="账号" align="center">
          <template #default="scope">
            <div v-html="scope.row.customerAccount"></div>
          </template>
        </el-table-column>
        <el-table-column prop="phoneNumber" label="手机号码" align="center">
          <template #default="scope">
            <div v-html="scope.row.phoneNumber"></div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" align="center">
          <template #default="scope">
            <div v-html="scope.row.name"></div>
          </template>
        </el-table-column>
        <el-table-column label="性别" align="center" width="80px">
          <template #default="scope">
            {{ SEXS[scope.row.sex + 1] }}
          </template>
        </el-table-column>
        <el-table-column prop="birthdayStr" label="生日" align="center" />
        <el-table-column prop="disable" label="禁用" align="center" width="80px">
          <template #default="scope">
            <span>{{ scope.row.disable ? "禁用" : "启用" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="200px">
          <template #default="scope">
            <el-button type="primary" :icon="Edit" circle
              @click="router.push(`/home/customer_detail/${scope.row.customerId}`)" />
            <el-button :icon="Check" circle v-if="scope.row.disable" @click="disableCustomer(scope.row, false)" />
            <el-button type="info" :icon="Close" circle v-else @click="disableCustomer(scope.row, true)" />
            <el-button type="danger" :icon="Delete" circle @click="deleteCustomerPrepare(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 客户分页域 -->
    <div class="customer-pagination-div-class">
      <el-pagination background layout="total, prev, pager, next, sizes" size="small" :total="customerTotal"
        v-model:page-size="customerPages.num" @update:page-size="queryCustomers()" :page-sizes="[10, 20, 50, 100]"
        v-model:current-page="customerPages.page" @update:current-page="queryCustomers()" />
    </div>
  </div>
  <!-- 客户删除域 -->
  <el-dialog header="确认删除" v-model="customerDeleteDialogDisable" width="300px">
    <span>您确定要删除这个客户吗？</span>
    <template #footer>
      <span>
        <el-button @click="customerDeleteDialogDisable = false">取消</el-button>
        <el-button type="primary" @click="deleteCustomerConfirm()">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.customer-page-div-class {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  gap: 15px;
  width: 100%;
  height: 100%;
  padding: 20px 20px 20px 20px;
}

.customer-table-div-class {
  flex: 1;
  width: 100%;
  overflow: hidden;
}

.customer-pagination-div-class {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  align-items: flex-end;
  width: 100%;
}

:deep em {
  font-style: normal;
  font-weight: bold;
  color: rgb(113, 6, 87);
}
</style>